function [pid129, pid131] = GET_OptimalPIDParameters(obj, varargin)
%GET_OPTIMALPIDPARAMETERS Summary of this function goes here
%   Detailed explanation goes here
    L = log4m.getLogger();
    
    p=inputParser;
    p.addParameter('order129', 8, @(x) isscalar(x) && ismember(x, 1:8));
    p.addParameter('order131', 8, @(x) isscalar(x) && ismember(x, 1:8));
    p.addParameter('bandwidth129', 20.35, @(x) isscalar(x) && x > 0 && x < 50);
    p.addParameter('bandwidth131', 20.35, @(x) isscalar(x) && x > 0 && x < 50);
    p.addParameter('tList', 0:0.001:0.25, @isnumeric);
    p.parse(varargin{:});
    
    order129 = p.Results.order129; bw129 = p.Results.bandwidth129; 
    
    %% Xe129
    L.info('XeNMRSystem::GET_OptimalPIDParameters', sprintf('Omptimizing Xe129 PID settings with order = %d, and bandwidth = %3.2f.', order129, bw129));
    gamma = obj.resonance129.gamma; % Hz 
    gain = 1.0/(2.0*pi*gamma)*360; % degree/Hz
    
    plant = EquipmentControl.FeedBackOptimization.LTIUnit.LowPassFilter(1, gamma, 'gain', gain);
    filter=EquipmentControl.FeedBackOptimization.LTIUnit.LowPassFilter(order129, bw129);
    tune = EquipmentControl.FeedBackOptimization.PIDOptimizer(plant, filter);
    tune.setControllerOptimal('type', 'PID', 'tList', p.Results.tList);
    
    [pval, ival, dval] = tune.getPIDValue();
    pid129.pValue = -pval; pid129.iValue = -ival; pid129.dValue = -dval;
    L.info('XeNMRSystem::GET_OptimalPIDParameters', sprintf('Omptimized Xe129 PID settings P=%5.3e, I=%5.3e, D=%5.3e.', pid129.pValue, pid129.iValue, pid129.dValue));
    
    %% Xe131
    order131 = p.Results.order131; bw131 = p.Results.bandwidth131;
    
    L.info('XeNMRSystem::GET_OptimalPIDParameters', sprintf('Omptimizing Xe131 PID settings with order = %d, and bandwidth = %3.2f.', order131, bw131));
    gamma = obj.resonance131.gamma; % Hz 
    gain = 1.0/(2.0*pi*gamma)*360; % degree/Hz
    
    plant = EquipmentControl.FeedBackOptimization.LTIUnit.LowPassFilter(1, gamma, 'gain', gain);
    filter=EquipmentControl.FeedBackOptimization.LTIUnit.LowPassFilter(order131, bw131);
    tune = EquipmentControl.FeedBackOptimization.PIDOptimizer(plant, filter);
    tune.setControllerOptimal('type', 'PID', 'tList', p.Results.tList);
    
    [pval, ival, dval] = tune.getPIDValue();
    pid131.pValue = -pval; pid131.iValue = -ival; pid131.dValue = -dval;
    
    L.info('XeNMRSystem::GET_OptimalPIDParameters', sprintf('Omptimized Xe131 PID settings P=%5.3e, I=%5.3e, D=%5.3e.', pid131.pValue, pid131.iValue, pid131.dValue));
    %%
    pid129.order = order129;
    pid129.bandwidth = bw129;
    pid131.order = order131;
    pid131.bandwidth = bw131;
    %%
    obj.pid129 = pid129;
    obj.pid131 = pid131;
    L.info('XeNMRSystem::GET_OptimalPIDParameters', 'PID Xe frequencies completed.');
end

